/**
 * Copyright (c) 2014-2015, Suredy technology Co., Ltd. All rights reserved.
 * 
 * @author ZhangMaoren
 * @since 2015年6月17日
 * @version 0.1
 */
package com.suredy.security.ctrl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.suredy.Constants;
import com.suredy.core.ctrl.BaseCtrl;
import com.suredy.core.mvc.model.MessageModel;
import com.suredy.security.entity.OrgEntity;
import com.suredy.security.entity.PermissionEntity;
import com.suredy.security.entity.Role2PermissionEntity;
import com.suredy.security.entity.RoleEntity;
import com.suredy.security.entity.User2RoleEntity;
import com.suredy.security.entity.UserEntity;
import com.suredy.security.model.Action;
import com.suredy.security.model.Org;
import com.suredy.security.model.Role;
import com.suredy.security.model.User;
import com.suredy.security.model.User2Role;
import com.suredy.security.service.OrgSrv;
import com.suredy.security.service.PermissionSrv;
import com.suredy.security.service.Role2PermissionSrv;
import com.suredy.security.service.RoleSrv;
import com.suredy.security.service.User2RoleSrv;
import com.suredy.security.service.UserSrv;

/**
 * @author ZhangMaoren
 *
 */
@Controller
@RequestMapping(value = "/config")
public class RoleCtrl extends BaseCtrl {

	private final static Logger log = LoggerFactory.getLogger(RoleCtrl.class);
	@Autowired
	private RoleSrv roleSrv;

	@Autowired
	private User2RoleSrv user2roleSrv;

	@Autowired
	private UserSrv userSrv;
	
	@Autowired 
	private OrgSrv orgSrv;
	
	@Autowired
	private PermissionSrv permissionSrv;
	
	@Autowired
	private Role2PermissionSrv role2permissionSrv;
	

	/**
	 * get role list
	 * 
	 * @param type
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "role/list")
	public ModelAndView getRoles(String page, String size) {
		ModelAndView view = new ModelAndView("/config/security/role-list");
		int pageIndex = 1, pageSize = Constants.DEFAULT_PAGE_SIZE;
		if (!StringUtils.isBlank(page)) {
			pageIndex = Integer.parseInt(page);
		} 
		if(!StringUtils.isBlank(size)) {
			pageSize = Integer.parseInt(size);
		}
		Long count = this.roleSrv.Count();
		List<Role> data = this.roleSrv.getAll(pageIndex, pageSize);
		
		view.addObject("data", data);
		view.addObject("pageSize", pageSize);
		view.addObject("pageIndex", pageIndex);
		view.addObject("count", count);
		return view;
	}
	
	@RequestMapping(value = "role/create")
	public ModelAndView createRole() {
		ModelAndView view = new ModelAndView("/config/security/role-create");
		List<Org> orgs = this.orgSrv.getAll();
		view.addObject("orgs", orgs);
		return view;
	}
	
	@RequestMapping("role/create-save")
	@ResponseBody
	public Object doCreateRole(HttpServletRequest request) {
		String orgId = request.getParameter("org");
		String code = request.getParameter("code");
		String name = request.getParameter("name");
		String alias = request.getParameter("alias");
		String sort = request.getParameter("sort");
		String description = request.getParameter("description");
		
		if (StringUtils.isBlank(orgId) || StringUtils.isBlank(code) || StringUtils.isBlank(name)) {
			return MessageModel.createErrorMessage("参数不足, 所属单位,角色代码,角色名称必须提供", null);
		}
		
		OrgEntity org = this.orgSrv.get(orgId);
		RoleEntity role = new RoleEntity();
		role.setAlias(StringUtils.isBlank(alias) ? null : alias);
		role.setAvailable(1);
		role.setBuildIn(0);
		role.setCode(code);
		role.setDescription(StringUtils.isBlank(description) ? null : description);
		role.setIsMailGroup(0);
		role.setName(name);
		role.setNotUserGroup(0);
		role.setOrg(org);
		role.setSort(StringUtils.isBlank(sort) ? null : Integer.parseInt(sort));
		role.setUniqueCode("G=" + code + "/" + org.getUniqueCode());
		this.roleSrv.save(role);
		
		return MessageModel.createSuccessMessage(null, null);
	}
	
	@RequestMapping(value = "role/edit")
	public ModelAndView editRole(String roleId) {
		ModelAndView view = new ModelAndView("/config/security/role-edit");
		if (StringUtils.isBlank(roleId)) {
			log.info("Parameter String[roleId] is blank.");
			return view;
		}
		List<Org> orgs = this.orgSrv.getAll();
		Role role = this.roleSrv.getById(roleId);
		view.addObject("orgs", orgs);
		view.addObject("role", role);
		return view;
	}
	
	@RequestMapping("role/edit-save")
	@ResponseBody
	public Object doEditRole(HttpServletRequest request) {
		String id = request.getParameter("id");
		String orgId = request.getParameter("org");
		String code = request.getParameter("code");
		String name = request.getParameter("name");
		String alias = request.getParameter("alias");
		String sort = request.getParameter("sort");
		String description = request.getParameter("description");
		
		if (StringUtils.isBlank(id) || StringUtils.isBlank(orgId) || StringUtils.isBlank(code) || StringUtils.isBlank(name)) {
			return MessageModel.createErrorMessage("参数不足, 角色ID, 所属单位,角色代码,角色名称必须提供", null);
		}
		
		OrgEntity org = this.orgSrv.get(orgId);
		RoleEntity role = this.roleSrv.get(id);
		role.setAlias(StringUtils.isBlank(alias) ? null : alias);
		role.setCode(code);
		role.setDescription(StringUtils.isBlank(description) ? null : description);
		role.setName(name);
		role.setOrg(org);
		role.setSort(StringUtils.isBlank(sort) ? null : Integer.parseInt(sort));
		role.setUniqueCode("G=" + code + "/" + org.getUniqueCode());
		this.roleSrv.update(role);
		
		return MessageModel.createSuccessMessage(null, null);
	}
	
	@RequestMapping("role/delete")
	@ResponseBody
	public Object doEditDelete(String roleId) {	
		if (StringUtils.isBlank(roleId)) {
			log.error("Parameter String[roleId] is blank.");
			return MessageModel.createErrorMessage("角色ID必须提供", null);
		}
		RoleEntity role = this.roleSrv.get(roleId);
		if (role == null) {
			return MessageModel.createErrorMessage("未找到与ID['"+ roleId +"']对应的角色信息", null);
		}
		
		this.roleSrv.delete(role);
		return MessageModel.createSuccessMessage(null, null);
	}

	@RequestMapping(value = "role/user")
	public ModelAndView Role2User(String roleId) {
		ModelAndView view = new ModelAndView("/config/security/role2user");
		Role role = this.roleSrv.getById(roleId);
		List<User> users = this.userSrv.getAll();
		List<User2RoleEntity> pos = this.user2roleSrv.getByRole(roleId);
		List<User2Role> relations = new ArrayList<User2Role>();
		for (User2RoleEntity po : pos) {
			relations.add(po.toVO());
		}
		view.addObject("role", role);
		view.addObject("relations", relations);
		view.addObject("users", users);
		return view;
	}

	@Transactional
	@RequestMapping("role/user-save")
	@ResponseBody
	public Object Role2UserSave(HttpServletRequest request) {
		String id = request.getParameter("id");
		if (StringUtils.isBlank(id)) {
			log.error("Parameter String[id] is blank.");
			return MessageModel.createErrorMessage("角色ID必须提供", null);
		}
		// 删除全部user2role引用
		List<User2RoleEntity> relations = this.user2roleSrv.getByRole(id);
		for (User2RoleEntity ur : relations) {
			this.user2roleSrv.delete(ur);
		}
		// 加入新的user2role引用
		String[] userIds = request.getParameterValues("userId");
		if (userIds != null && userIds.length > 0) {
			for (String userId : userIds) {
				User2RoleEntity ur = new User2RoleEntity();
				RoleEntity role = new RoleEntity();
				role.setId(id);
				UserEntity user = new UserEntity();
				user.setId(userId);
				ur.setRole(role);
				ur.setUser(user);
				this.user2roleSrv.save(ur);
			}
		}
		return MessageModel.createSuccessMessage(null, null);
	}
	
	@RequestMapping(value = "role/permission")
	public ModelAndView Role2Permission(String roleId) {
		ModelAndView view = new ModelAndView("config/security/role2permission");
		Role role = this.roleSrv.getById(roleId);
		view.addObject("role", role);
		return view;
	}
	
	@Transactional
	@RequestMapping("role/permission-save")
	@ResponseBody
	public Object Role2PermissionSave(HttpServletRequest request) {
		String id = request.getParameter("id");
		if (StringUtils.isBlank(id)) {
			log.error("Parameter String[id] is blank.");
			return MessageModel.createErrorMessage("角色ID必须提供", null);
		}
		
		//删除全部role2permission引用
		List<Role2PermissionEntity> rolePermissions = this.role2permissionSrv.getByRole(id);
		for (Role2PermissionEntity rp : rolePermissions) {
			this.role2permissionSrv.delete(rp);
		}
		
		for (Action action : Action.values()) {			
			//新的role2permission引用
			String data =  request.getParameter("resources");
			if (!StringUtils.isBlank(data)) {
				String[] resourceIds = data.split("-");
				if (resourceIds != null && resourceIds.length > 0) {
					for (String resourceId : resourceIds) {
						PermissionEntity permission = this.permissionSrv.GetOrCreate(resourceId,  action.getAction());
						Role2PermissionEntity rp = new Role2PermissionEntity();
						rp.setPermission(permission);
						RoleEntity role = new RoleEntity();
						role.setId(id);
						rp.setRole(role);
						this.role2permissionSrv.save(rp);
					} 
				}
			}
		}

		return MessageModel.createSuccessMessage(null, null);
	}

}
